package com.mh.study.dubbo.loadblance;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.LoadBalance;

import java.util.List;

/**
 * @author meng.han
 * @since 2022-01-24
 */
public class OnlyFirstLoadbalancer implements LoadBalance {
    @Override
    public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
        // 所有的服务提供者 按照IP  + 端口排序   选择第一个
        return invokers.stream().min((i1, i2) -> {
            URL url1 = i1.getUrl();
            URL url2 = i2.getUrl();
            System.out.printf("ip1: %s, port1: %s \n",url1.getIp(), url1.getPort());
            System.out.printf("ip2: %s, port2: %s \n",url2.getIp(), url2.getPort());
            final int ipCompare = url1.getIp().compareTo(url2.getIp());
            if (ipCompare == 0) {
                return Integer.compare(url1.getPort(), url2.getPort());
            }
            return ipCompare;
        }).orElseThrow();
    }
}
